import axios from 'axios'
import { getToken } from './auth'

// 创建 axios 实例
const http = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
  timeout: 10000
})

// 缓存配置
const CACHE_CONFIG = {
  // 缓存过期时间（毫秒）- 10分钟
  ttl: 60 * 60 * 1000,
  // 不需要缓存的路径前缀
  excludePaths: ['/user', '/auth', '/progress', '/vocabulary', '/visits'],
  // 数据库名称和版本
  dbName: 'HttpCache',
  dbVersion: 1
}

// IndexedDB 数据库实例
let dbInstance = null

// 打开或创建 IndexedDB 数据库
function openDatabase() {
  return new Promise((resolve, reject) => {
    if (dbInstance) {
      return resolve(dbInstance)
    }

    const request = indexedDB.open(CACHE_CONFIG.dbName, CACHE_CONFIG.dbVersion)

    request.onerror = () => {
      console.error('Failed to open cache database:', request.error)
      reject(request.error)
    }

    request.onsuccess = () => {
      dbInstance = request.result
      resolve(dbInstance)
    }

    request.onupgradeneeded = (event) => {
      const db = event.target.result
      if (!db.objectStoreNames.contains('cache')) {
        const store = db.createObjectStore('cache', { keyPath: 'id' })
        store.createIndex('expiresAt', 'expiresAt', { unique: false })
      }
    }
  })
}

// 生成缓存键
function generateCacheKey(config) {
  return `${config.method}:${config.url}:${JSON.stringify(config.params || {})}`
}

// 检查是否应该缓存该请求
function shouldCacheRequest(config) {
  // 只缓存 GET 请求
  if (config.method !== 'get') {
    return false
  }

  // 检查是否在排除列表中
  try {
    if(window.location.href.indexOf("localhost") > -1){
      return false;
    }
    if(window.location.href.indexOf("127.0") > -1){
      return false;
    }
    const urlPath = new URL(config.url, 'http://dummy').pathname
    return !CACHE_CONFIG.excludePaths.some((path) => urlPath.startsWith(path))
  } catch (e) {
    // 如果 URL 解析失败，不缓存
    return false
  }
}

// 从 IndexedDB 缓存中获取数据
async function getFromCache(key) {
  try {
    const db = await openDatabase()
    const transaction = db.transaction(['cache'], 'readonly')
    const store = transaction.objectStore('cache')
    const request = store.get(key)

    return new Promise((resolve) => {
      request.onsuccess = () => {
        const result = request.result
        if (!result) {
          return resolve(null)
        }

        const now = Date.now()
        // 检查是否过期
        if (now > result.expiresAt) {
          // 删除过期项
          const deleteTransaction = db.transaction(['cache'], 'readwrite')
          const deleteStore = deleteTransaction.objectStore('cache')
          deleteStore.delete(key)
          return resolve(null)
        }

        resolve(result.data)
      }

      request.onerror = () => {
        console.warn('Error reading from cache:', request.error)
        resolve(null)
      }
    })
  } catch (error) {
    console.warn('Error opening database:', error)
    return null
  }
}

// 将数据存入 IndexedDB 缓存
async function saveToCache(key, data) {
  try {
    const db = await openDatabase()
    const transaction = db.transaction(['cache'], 'readwrite')
    const store = transaction.objectStore('cache')

    const cacheItem = {
      id: key,
      data: data,
      expiresAt: Date.now() + CACHE_CONFIG.ttl
    }

    store.put(cacheItem)
  } catch (error) {
    console.warn('Error saving to cache:', error)
  }
}

// 请求拦截器
http.interceptors.request.use(
  async (config) => {
    // 检查是否应该缓存该请求
    if (shouldCacheRequest(config)) {
      const cacheKey = `http_cache:${generateCacheKey(config)}`
      const cachedData = await getFromCache(cacheKey)

      if (cachedData) {
        // 如果有缓存数据，直接返回
        config.adapter = function () {
          return Promise.resolve({
            data: cachedData,
            status: 200,
            statusText: 'OK',
            headers: config.headers,
            config: config,
            request: {}
          })
        }
      } else {
        // 保存缓存键，以便在响应拦截器中使用
        config.cacheKey = cacheKey
      }
    }

    // 可以在这里统一添加请求头
    // 例如添加认证 token
    const token = getToken()
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }

    // 添加统一的请求头
    config.headers['Content-Type'] = 'application/json'

    // 可以根据需要添加其他请求头
    // config.headers['X-Requested-With'] = 'XMLHttpRequest';

    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
http.interceptors.response.use(
  async (response) => {
    // 对响应数据做些统一处理
    const data = response.data

    // 如果有缓存键，则将响应数据存入缓存
    if (response.config.cacheKey) {
      await saveToCache(response.config.cacheKey, data)
    }

    return data
  },
  (error) => {
    // 对响应错误做些统一处理
    if (
      error.response &&
      (error.response.status === 401 || error.response.status === 400)
    ) {
      // Token 过期或无效，清除本地存储
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      // 可以在这里添加跳转到登录页的逻辑
      // window.location.href = '/login';
      // 浏览器刷新一次
      window.location.reload()
    }
    return Promise.reject(error)
  }
)

export default http

// 为了方便替换现有的 axios.get 等调用，导出这些方法
export const get = http.get
export const post = http.post
export const put = http.put
export const del = http.delete
export const patch = http.patch

// 导出清除缓存的方法
export async function clearCache() {
  try {
    const db = await openDatabase()
    const transaction = db.transaction(['cache'], 'readwrite')
    const store = transaction.objectStore('cache')
    store.clear()
  } catch (error) {
    console.warn('Error clearing cache:', error)
  }
}
